""" 程序主入口。构建窗口 """

import sys,os
import PySimpleGUI as sg 
from datetime import datetime
from datetime import timedelta
from openpyxl import Workbook
# import pandas as pds
from sqlhlper import SQLHLPER
import otherwindow as otherwin
from objects import MR
import re

# ------函数和类------------

""" 根据关键字查询病案并更新table控件函数 """
def update_table():
    
    fdate=datetime(1900,1,1).date()
    ldate=datetime.now().date()

    if mainwin['-firstdate-'].Get()!='':
        fdate=datetime.strptime(mainwin['-firstdate-'].Get(),'%Y-%m-%d').date()
    elif values['-in-']=='':
        fdate=datetime.now().date()-timedelta(100)        

    if mainwin['-lastdate-'].Get()!='':
        ldate=datetime.strptime(mainwin['-lastdate-'].Get(),'%Y-%m-%d').date()

    if ldate<fdate:
        sg.PopupError('截止日期应等于或晚于开始日期！')
        return   


    #查询数据库
    if values['-only_borrowed_mr-']:
        sqlstr='select case is_on when 1 then "在档" else "借" end,mr_num,HOSPITAL_NUM,PAT_NAME,ID_NUM,IN_DATE,DIS_DATE,DIS_WAY,DIS_GROUP,DOCTOR,pd,ADDR,filing_time,ID from mrinfo where is_on=0 and date(dis_date)>=:fdate and date(dis_date)<=:ldate and (mr_num =:keyword or HOSPITAL_NUM=:keyword or DIS_WAY like :keyword2 or PAT_NAME LIKE :keyword2 or ID_NUM LIKE :keyword2) ORDER BY FILING_TIME DESC,DIS_DATE DESC,PAT_NAME'
    else:
        sqlstr='select case is_on when 1 then "在档" else "借" end,mr_num,HOSPITAL_NUM,PAT_NAME,ID_NUM,IN_DATE,DIS_DATE,DIS_WAY,DIS_GROUP,DOCTOR,pd,ADDR,filing_time,ID from mrinfo where date(dis_date)>=:fdate and date(dis_date)<=:ldate and (mr_num =:keyword or HOSPITAL_NUM=:keyword or DIS_WAY like :keyword2 or PAT_NAME LIKE :keyword2 or ID_NUM LIKE :keyword2) ORDER BY FILING_TIME DESC,DIS_DATE DESC,PAT_NAME'

    try:
        res=SQLHLPER.selectall(sqlstr,**{'keyword':values['-in-'],'keyword2':'%'+values['-in-']+'%','fdate':fdate,'ldate':ldate})
    except Exception as e:
        sg.Print(str(e))
        return

    t_data=[list(item) for item in res]

    mainwin['-table-'].Update(t_data)
    mainwin['-table-'].Update(num_rows=min(len(t_data),20))
    mainwin['-display_rows-'].Update('查询到 {} 条病案记录'.format(len(t_data)))




# ------下面构建主窗口---------

# 构建工具栏
# 归档图标
img_data_filing='iVBORw0KGgoAAAANSUhEUgAAACIAAAAgCAYAAAB3j6rJAAABQElEQVRYhe2YsUrEQBCGU9jJwe2MeI0PYGFhJ1j5ENaSR7jW7gSfwLudxUIEQbC70jJISkHr7AzYiLETfAGthHBcks1uPKNm4S/nn4/9s+xkI0WcdEEREH90QQUQScHI5UpFki4B4XG04oXaxj3I3wMB4jHobFIpR69QkMf64yhPPUgP8j9BcJptD6d8UBQQ5w6XWL5Yp4zseIMMtd0FzRcOjSuFxNc4s3tB0YyuXteR+BjIvnhAvAHxyWD2jEHRFBdoPgTDd84QRu5RZ0dVnt4fa4OobkDLfp1f0KmpiepdGXs6MrLp4tXK7bsYFRI/oJG4iUdrY8DgPNsA4lsgSeGMt5rWtz+PTJI1n7JuD0aKZF426KC2cVCzEl9FMl+2I6VSxIkvSLFZlXqQ3w0CxLn/b6XT2OAM8u2Kfvo54kufbFWIkRRe7BwAAAAASUVORK5CYII='
# 查看全部已归档图标
img_data_mrr='iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABG0lEQVRYhe2WoU7EQBCGT5yEZHeWvkElog+ArDyBRCAqEJVIBKLuZAWZmZCKPgKP0AdAIAi5dGaSEycRPAKYI7lLLy2Hvf2SMZv5//3kzGaRSOQAnu0yoBSAfQWkDbC1gXXpScpAks+qbj4IVd08kOSepAysS2Brga3ddtw5lGz00wQ/zjxJCWyvQPo9MZ9A2iRoaYKWAmmzfZvKvQHpvavXbiAApPUfCvYmoBQBpTg259mehgJs7b8EqL8+WoDsJQpEgSgQBaJAFIgC0wKsG2BdedLud4B1BTuHx4F74GuQIX0H1s1+t7UDAY/9VSB59CyL8+f+YrCwQ4KWeu5vHErmUDJPepugpWMZV6+dZ1l41IdAko/tRiKnxQ8R9f/unL+u/QAAAABJRU5ErkJggg=='
# 查看复印记录图标
img_data_mrcopyedrecord='iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAB/UlEQVRYhe2XoW8UQRSHV1RUnEBwyd68SVhRQYJBnDiBOFGBQECCRJyoKEnFCUpm3hzJKpAYEhIQJyoqKhCIk/wBFSWpqCFBVNS3CRUnPkR3L8deSXO7e3dAeMnPbGZnv3nzfm92olagbQIjUViwTkTpRcUQZX8JH8/1rRW4UwQYi4JxbFpHd1HKs2wCD4oAiMJMamoOCbwVBevo/gf48wFE6YkyLCujfDSeu4U5h/MAnFS2XGC7NECyS1zFchLoRClrpQEWEX9XEa4cQDwD8XyZVyYwkkDnWoCluaBQ/aUAkpT12JHMq2SX+LdbsHIXePqijK1jYyUAUXSV2VmyJQJcG/8cgLzEiueRKD3xDIznhSg96+g2UxoLAUhS1sUzEOXoBptemsDIeB7XBiDK/am+cSHKgQS2xfPceD5YzzurbImnn/0XXmZj95spjUoAzZSGKKeijE3gTV7lsSPJYPKVH+Wno0m5LcpeDlEJwDg2s/cPCll5XUy/DTyZDEhZM4EzUS4qAVjHRrb6s+kz4CYAq2yJglUOq9dA1uGyCT9Z5ZkEOr9sgedr/Ip74ulb5TB7ftoKtGtxQSvQnpp4IqOci/Kj6ARR9pKUW3m6ausDWQ/oizKUwOfJUX11/XsvnqczvWDlnXDqZvx9Dh1bx8NaAEpez8fGsVPH938CttLYcHtMzmoAAAAASUVORK5CYII='
# 其它档案借阅登记
img_data_reginotherrecord='iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAB70lEQVRYhe2XPWsbQRCGF0eKXTiwOxdBChcqXIRU/gEuVAaiwoUh/gEuU6Rw4SZwzpdLgcTMRpVKgYqkSKEmcIVt3LgLRuzNgkqXKV0Eci58KJKi0+3pMwl6YZr9ep+d3bu5E2Klv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Dovz5HLrtB8yVhQRNAAXKeAu1q0h11txqt3zuwcYyY0KekHgz1/H/7oiiv06JK+bm83tWdzeWCx6dnHTKOcfEqUNiaiMQ++Hguve750u2FDuiayftILmhqgZvcJJin5AV5L1k3AFJ+woUrrgcSKNYtqyojCC5fWQCr9mBQu2T/01++vXF7/5ogNhHPQzAAAAAElFTkSuQmCC'
# 主窗口搜索图标
img_data_search='iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAB9ElEQVRYhe2WIUzDUBCGP7EEBAKxBDMxMTExOTGBQCAImUBMIBAViIkJSBBIEgQCiUCgAIGYRJCAQEAyQQICMbGECUhIQCAmJhBD3L28x9KNvbZUEC6p2K3/3feuvbvCv01uJaAGBHotAjNpJK4DHWAQcvWBJpD/jcR54NpJ1gZOgQ1gH7gCevpfD6lKYlZzgl8z/oQN595zIBM3eQ740KANx1/Gnjw3pCkAdwqxEyf5FHCsgTbVlwF2gU/s48iHaEvALfACLEcFCLBlN3agvmdgFciO0Vf13gciPooHvp9wQX93gdkJY5ypZtE3eUGFHcfXVN+SR5w11Rz6AtRUeOL47oEn/AZOReNc+gIEKtwa8lV9AyEd1PYVrZNAGwFzwBtw4ytcwg6TOFbWOE1fYRbp9feYAA0F2I0ivlLxQgyAG41RiCKuIFXoANMR9Ob0d1GSG9vXIHueujx2KQ2QrRnJppEWGiBjeJIZUEVGtQF/jQtRwo7lriYIAylgd4XbQcUkIDLITHC34CPyUXKBrGzjf0XK/4lM1MQgQKpxhLSn+znWA1rI7M8A8yMgzHsRC8JYFnnZRq3kMAjjSwziJ/sJojFCl6itKEAYRJ+UPudrIRB1pApBGgDDENvYUV9OC8BA9LHd00ozubEi0gEB0XbMH7Yv1filjU9VD18AAAAASUVORK5CYII='
#其它档案历史记录查阅图标
img_data_archiveshistory='iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACKklEQVRYhe2XoW/bQBTGDQICAu6eZykgwGCgYKBgoGCgYGBgYKCgf8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n+Gn7Zm74IYePc1Hm3wPumFD6fBc6fC83onr2fF45JLIroQf1JJl56GnH/azyALyjeN7k53Uwz4YGrhxN/aEbTgn82xwIYRIVWqc57sg4VRCh37KIW469zXNKrtrytCVk9XlNn+L8bLCcK7CzvkckOYKo/a2YEuThlvScKuov9LhudPcHSGE7djVkpn81y2WNj+o2Q06B6SZ8IOagGs6XbKSSD92Bm5NIX1/q8I1nQpA6i1/yFsyaQPNn8HwCAyPFEYnRc95mo9W181G2FU6B6RJmUyS882jcmcXEySRAgGa7mygP6WCpPZ+ybO3i3GkOwGGnuwo/X5HAr/s/ngSgPRsg7w/AaRnAYY/4Ar41vbOXfUm/BcCiSasOoYVCbhjCEg9IQ2fVVlEVQm4i0gaPqu8iisRSK3iNyyFbFZ/ldHFrggA0tfEFlya/atcVmFaRL+VJXDQDRuw0oqzNYykIOHRVkGC9OoQeM1FX5Q+WFU5JUiWTglJZmiQK8lcmWVokAdeSJIJsUmU8ijrOjwdN0GHPujQz/I56IaNROa5otTaBlk+kRh9K/W48IOabbiJC75VlieySz9MDD0qjNp5etHTfKQwajujVv5hksgi62lmaCyRAjA0AEMD+3285lf1abZejY94nKZsV8/zv+zTthew1ggGAAAAAElFTkSuQmCC'
# calendar
img_data_calendar='iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAiElEQVQ4jbWR0QmAMBBD3wgdwRG6gY7iJnYzb4O6gY7ih1c8tSitGgg0vRACgY8RgO7m3qnnAgFGYAaivnOM6kn6EFDaQOwhiQZwNwFOPZeARZNLuOQalEByQpQ94I32+icn7z8NRtMgzZUa2Pn+aRCAgW3vRt8D+3SPAdUNJqAtZLQBoZLvsQItcDy/JhvEGAAAAABJRU5ErkJggg=='


# 设置pysimplegui全局参数
sg.SetOptions(margins=(8,5),auto_size_buttons=True,button_color=('black','white'),font=('Microsoft YaHei',10))


# 一些工具栏上按钮的设置
pd=(1,1)   #pad=(1,1)
bw=1       #border_width=0

toolbar_buttons=[
    sg.B('',image_data=img_data_filing,key='-mr_filing-',tooltip='病案归档',pad=pd,border_width=bw),
    sg.B('',image_data=img_data_filingrate,key='-mr_filingrate-',tooltip='病案归档率',pad=pd,border_width=bw),
    sg.B('',image_data=img_data_mrr,key='-mr_borrowed_log-',tooltip='查看病案借阅历史记录',pad=pd,border_width=bw),
    sg.B('',image_data=img_data_mrcopyedrecord,key='-mr_copyed_log-',tooltip='查阅病历复印历史记录',pad=pd,border_width=bw),
    sg.B('',image_data=img_data_option,key='-option-',tooltip='选项',pad=pd,border_width=bw),
    sg.Text('',size=(1,1)),
    sg.B('',image_data=img_data_reginotherrecord,key='-arc_borrow-',tooltip='其它档案借阅登记',pad=pd,border_width=bw),
    sg.B('',image_data=img_data_archiveshistory,key='-arc_bor_log-',tooltip='其它档案归还查阅历史记录',pad=pd,border_width=bw),
    sg.Text('',size=(1,1)),
    sg.B('',image_data=img_data_help,key='-help-',tooltip='帮助信息',pad=pd,border_width=bw)
]


# 预设表格控件table

t_right_click_menu=['menu',['借阅::-borrow-','归还::-giveback-','复印::-becopy-','修改::-edit-','----','导出::-export-']]   # 表格控件的右键菜单

headings=['在档','病案号','住院号','患者姓名','身份证号','入院日期','出院日期','离院方式','出院科室','住院医生','主要诊断','患者住址','归档时间','id']
visible_col_map=[True]*13+[False]
# t_header=[' '+h for h in headings]   #表头
t_data=[[' '*4,' '*7,' '*8,' '*8,' '*20,' '*11,' '*11,' '*8,' '*8,' '*8,' '*22,' '*20,' '*20,' '*5]]

table=sg.Table(values=t_data,headings=headings,key='-table-',def_col_width=None,num_rows=None,
auto_size_columns=True,display_row_numbers=True,enable_events=True,vertical_scroll_only=False,alternating_row_color='alice blue',
right_click_menu=t_right_click_menu,row_height=25,visible_column_map=visible_col_map)


month_names_list=[str(m)+'月' for m in range(1,13)]   #calendar 的自定义月份列表
day_abbreviations_list=['周一','周二','周三','周四','周五','周六','周日']    #calendar 的自定义星期列表


# mainwindow的layout
layout=[toolbar_buttons,
[sg.Text('',key='-emptxt-',size=(1,10),background_color=None)],
[sg.Column(layout=[
    [sg.Input('',key='-in-',size=(50,1),pad=((2,2),(3,5)),font=('microsoft yahei',18),focus=True),
    sg.B('',key='-search-',image_data=img_data_search,pad=pd,border_width=bw,bind_return_key=True)],
    [sg.Checkbox('仅查询借出档案',key='-only_borrowed_mr-'),sg.Text('',size=(6,1)),
    sg.Text('',size=(12,1),key='-firstdate-',justification='right'),sg.Button('',image_data=img_data_calendar,key='-firstdate_calendar-',tooltip='单击选择起始日期'),
    sg.Text('',size=(12,1),key='-lastdate-',justification='right'),sg.Button('',image_data=img_data_calendar,key='-lastdate_calendar-',tooltip='单击选择截止日期,等于或晚于起始日期')]
],
justification='center',element_justification='left',size=(None,None),key='-mainframe-',background_color=None)],
[sg.Column(layout=[[table],[sg.Text('',size=(30,1),key='-display_rows-')]],justification='center',background_color=None,visible=False,key='-tablecol-')]
]


# 创建主窗口mainwin

mainwin=sg.Window('MRMS',layout,return_keyboard_events=False,use_default_focus=False,
resizable=True,background_color=None,size=(1200,800),finalize=True)
mainwin.Maximize()    #窗口最大化

borrowwin_active=False      #借阅登记窗口状态变量，默认False,当前未激活
filingratewin_active=False  #病案归档率窗口状态变量
backwin_active=False        #归还登记窗口状态变量
copywin_active=False        #复印登记窗口状态变量
mr_editwin_active=False     #修改归档病案信息窗口状态变量
filingwin_active=False            #病案归档窗口状态变量
mr_bor_logwin_active=False        #查阅病案全部借阅记录
mr_cop_logwin_active=False        #查阅病案全部复印历史记录
arc_bor_logwin_active=False       #其它档案借阅查阅窗口
arc_borrowwin_active=False        #其它档案借阅登记窗口
arc_backwin_active=False          #其它档案归还窗口
optionwin_active=False            #选项设置窗口
helpwin_active=False              #查看帮助信息
dayoffwin_active=False            #非工作日管理窗口



while True:
    event,values=mainwin.Read(timeout=100)
    if event is None or event == 'OK':
        break


    if event=='-firstdate_calendar-':
        choosen_time=otherwin.PopupCalendar(format='%Y-%m-%d')
        mainwin['-firstdate-'].Update(choosen_time)

    if event=='-lastdate_calendar-':
        choosen_time=otherwin.PopupCalendar(format='%Y-%m-%d')
        mainwin['-lastdate-'].Update(choosen_time)


    #-------------搜索查询事件-----------------
    if event=='-search-':     # or (event == '\r' and mainwin.FindElementWithFocus().Key=='-in-'):
        mainwin['-emptxt-'].set_size(size=(1,1))     #设置占位控件为1行高
               
        update_table()
        mainwin['-tablecol-'].Update(visible=True)
      


    # ------------借阅登记事件-----------------
    if event=='借阅::-borrow-' and not borrowwin_active:
        if len(values['-table-'])==0:
            continue
        # print(values['-table-'],t_data)
        borrowwin_active=True
        t_data=mainwin['-table-'].Get()               #获取table控件的值，即数据列表（list）
        selected_row=t_data[values['-table-'][0]]     #获取table控件当前选中行，一维的list对象
        if selected_row[0]=='借':
            sg.Popup('病案已借出，暂未归还！\n病案号：{0}\n住院号：{1}\n姓名：{2}'.format(selected_row[1],selected_row[2],selected_row[3]))
            borrowwin_active=False
            continue

        
        borrowwin_layout=[
            [sg.T(selected_row[-1],key='-id-',visible=False)],
            [sg.T('病案号:',size=(10,1)),sg.T(selected_row[1],key='-mr_num-')],
            [sg.T('住院号:',size=(10,1)),sg.T(selected_row[2],key='-hospital_num-')],
            [sg.T('患者姓名:',size=(10,1)),sg.T(selected_row[3],key='-pat_name-')],
            [sg.T('借阅人：',size=(10,1)),sg.I('',key='-borrower-',size=(20,1))],
            [sg.T('借阅时间:',size=(10,1)),sg.I(datetime.now().strftime('%Y-%m-%d %H:%M:%S'),key='-borrow_time-',size=(20,1)),
            sg.Button('',image_data=img_data_calendar,key='-calendar-')],
            [sg.T('',size=(1,3))],
            [sg.Button(' 保存 ',key='-save-',bind_return_key=True),sg.Button(' 取消 ',key='-cancel-')]
        ]

        borrowwin=sg.Window('借阅登记',borrowwin_layout,size=(500,300),font=('Microsoft YaHei',11))
    
    if borrowwin_active:
        borrowwin_event,borrowwin_values=borrowwin.Read(timeout=100)

        if borrowwin_event is None or borrowwin_event=='-cancel-':
            borrowwin_active=False
            borrowwin.close()

        if borrowwin_event == '-calendar-':
            choosen_time=otherwin.PopupCalendar()
            borrowwin['-borrow_time-'].Update(choosen_time)

        # 借阅登记记录入数据库
        if borrowwin_event=='-save-':
            borrower=borrowwin_values['-borrower-']
            borrow_time=borrowwin_values['-borrow_time-']
            if borrower=='' or borrow_time=='':
                sg.Popup('借阅人、借阅时间不能为空！\n 时间格式：yyyy-mm-dd HH:MM:SS')
                continue
            
            sqlstr1="insert into mrborrow(mrinfo_id,borrower,borrow_time) values({0},'{1}','{2}');".format(int(borrowwin['-id-'].Get()),borrower,borrow_time)
            sqlstr2="update mrinfo set is_on=0 where id={};".format(int(borrowwin['-id-'].Get()))         #病案在档状态修改为0，表示不在档
            sqlstr=sqlstr1+sqlstr2
            rs=SQLHLPER.executescript(sqlstr)
            if rs==2:
                borrowwin_active=False
                borrowwin.close()

                update_table()


    # ------------归还借阅病案-----------------
    if event=='归还::-giveback-' and not backwin_active:
        if len(values['-table-'])==0:
            continue
        backwin_active=True
        t_data=mainwin['-table-'].Get()
        selected_row=t_data[values['-table-'][0]]     #获取table控件当前选中行，一维的list对象
        if selected_row[0]=='在档':
            sg.Popup('病案未借出，不用归还!\n病案号：{0}\n住院号：{1}\n姓名：{2}'.format(selected_row[1],selected_row[2],selected_row[3]))
            backwin_active=False
            continue

        # 构建窗口
        backwin_layout=[
            [sg.T(selected_row[-1],key='-id-',visible=False)],
            [sg.T('病案号:',size=(10,1)),sg.T(selected_row[1],key='-mr_num-')],
            [sg.T('住院号:',size=(10,1)),sg.T(selected_row[2],key='-hospital_num-')],
            [sg.T('患者姓名:',size=(10,1)),sg.T(selected_row[3],key='-pat_name-')],
            [sg.T('归还时间:',size=(10,1)),sg.I(datetime.now().strftime('%Y-%m-%d %H:%m:%S'),key='-giveback_time-',size=(20,1)),
            sg.Button('',image_data=img_data_calendar,key='-calendar-')],
            [sg.T('',size=(1,3))],
            [sg.Button(' 保存 ',key='-save-',bind_return_key=True),sg.Button(' 取消 ',key='-cancel-')]
        ]

        backwin=sg.Window('归还病案',backwin_layout,size=(500,300),font=('Microsoft YaHei',11))
    
    if backwin_active:
        backwin_event,backwin_values=backwin.Read(timeout=100)

        if backwin_event is None or backwin_event=='-cancel-':
            backwin_active=False
            backwin.close()

        if backwin_event=='-calendar-':
            choosen_time=otherwin.PopupCalendar()
            backwin['-giveback_time-'].Update(choosen_time)

        # 归还病案记录入数据库
        if backwin_event=='-save-':
            giveback_time=backwin_values['-giveback_time-']
            # 这里还应该验证时间格式
            if giveback_time=='':
                sg.PopupError('警告','归还时间不能为空，格式为：yyyy-mm-dd HH:MM:SS 或 yyyy-mm-dd')
                continue

            sqlstr1="update mrborrow set back_time='{0}' where mrinfo_id={1}  and back_time is NULL;".format(giveback_time,int(backwin['-id-'].Get()))
            sqlstr2="update mrinfo set is_on=1 where id={};".format(int(backwin['-id-'].Get()))
            sqlstr=sqlstr1+sqlstr2
            rs=SQLHLPER.executescript(sqlstr)
            print(rs)
            if rs==2:
                backwin_active=False
                backwin.close()

                update_table()


    # -------------复印登记--------------------
    if event=='复印::-becopy-' and not copywin_active:
        if len(values['-table-'])==0:
            continue
        copywin_active=True
        t_data=mainwin['-table-'].Get()
        selected_row=t_data[values['-table-'][0]]     #获取table控件当前选中行，一维的list对象

        copywin_layout=[
            [sg.T(selected_row[-1],key='-id-',visible=False)],
            [sg.T('病案号:',size=(15,1)),sg.T(selected_row[1],key='-mr_num-')],
            [sg.T('住院号:',size=(15,1)),sg.T(selected_row[2],key='-hospital_num-')],
            [sg.T('患者姓名:',size=(15,1)),sg.T(selected_row[3],key='-pat_name-')],
            [sg.T('复印人姓名：',size=(15,1)),sg.I('',key='-copyer_name-',size=(20,1))],
            [sg.T('复印人身份证号:',size=(15,1)),sg.I('',key='-copyer_id_num-',size=(20,1))],
            [sg.T('与患者关系',size=(15,1)),sg.I('',key='-relation-',size=(20,1))],
            [sg.T('复印件用途',size=(15,1)),sg.I('',key='-purpose-',size=(20,1))],
            [sg.T('复印时间:',size=(15,1)),sg.I(datetime.now().strftime('%Y-%m-%d %H:%m:%S'),key='-copy_time-',size=(20,1)),
            sg.Button('',image_data=img_data_calendar,key='-calendar-')],
            [sg.T('',size=(1,3))],
            [sg.Button(' 保存 ',key='-save-',bind_return_key=True),sg.Button(' 取消 ',key='-cancel-')]
        ]

        copywin=sg.Window('复印病历登记',copywin_layout,size=(600,400),font=('Microsoft YaHei',12))

    if copywin_active:
        copywin_event,copywin_values=copywin.Read(timeout=100)

        if copywin_event is None or copywin_event =='-cancel-':
            copywin_active=False
            copywin.close()

        if copywin_event=='-calendar-':
            choosen_time=otherwin.PopupCalendar()
            copywin['-copy_time-'].Update(choosen_time)
        
        # 复印记录入数据库
        if copywin_event=='-save-':

            copyer_name=copywin_values['-copyer_name-']
            copyer_relation=copywin_values['-relation-']
            copyer_purpose=copywin_values['-purpose-']
            copy_time=copywin_values['-copy_time-']

            if copyer_name=='' or copyer_relation=='' or copyer_purpose=='' or copy_time=='':
                sg.PopupError('复印人姓名、关系、用途、复印时间必填！\n 时间格式：yyyy-mm-dd HH:MM:SS 或 yyyy-mm-dd') 
                continue

            sqlstr="insert into mrcopyrecord(mrinfo_id,copyer_name,copyer_id_num,relation,purpose,copy_time) values(?,?,?,?,?,?)"
            rs=SQLHLPER.execute(sqlstr,*(int(copywin['-id-'].Get()),copyer_name,copywin_values['-copyer_id_num-'],copyer_relation,copyer_purpose,copy_time))
            if rs==1:
                copywin_active=False
                copywin.close()



    # -------------编辑归档病案信息--------------

    if event=='修改::-edit-' and not mr_editwin_active:

        if len(values['-table-'])==0:
            continue
        mr_editwin_active=True
        t_data=mainwin['-table-'].Get()
        selected_row=t_data[values['-table-'][0]]     #获取table控件当前选中行，一维的list对象

        mr=MR(id=selected_row[13],mr_num=selected_row[1],hospital_num=selected_row[2],pat_name=selected_row[3],
        id_num=selected_row[4],pd=selected_row[10],in_date=selected_row[5],dis_date=selected_row[6],dis_group=selected_row[8],
        doctor=selected_row[9],dis_way=selected_row[7],addr=selected_row[11],is_on=selected_row[0],filing_time=selected_row[12])

        mr_editwin=otherwin.MREditWindow(mr)

    if mr_editwin_active:

        mr_editwin_event,mr_editwin_values=mr_editwin.Read(timeout=100)

        if mr_editwin_event is None or mr_editwin_event=='-cancel-':
            mr_editwin_active=False
            mr_editwin.close()

        if mr_editwin_event=='-in_date_calendar-':
            choosen_time=otherwin.PopupCalendar(format='%Y-%m-%d')
            mr_editwin['-in_date-'].Update(choosen_time)

        if mr_editwin_event=='-dis_date_calendar-':
            choosen_time=otherwin.PopupCalendar(format='%Y-%m-%d')
            mr_editwin['-dis_date-'].Update(choosen_time)

        if mr_editwin_event=='-filing_time_calendar-':
            choosen_time=otherwin.PopupCalendar()
            mr_editwin['-filing_time-'].Update(choosen_time)

        if mr_editwin_event=='-save-':

            custon_mr=MR()    #创建一个MR对象
            try:
                custon_mr.mr_num=mr_editwin_values['-mr_num-']
                custon_mr.hospital_num=mr_editwin_values['-hospital_num-']
                custon_mr.pat_name=mr_editwin_values['-pat_name-']
                custon_mr.id_num=mr_editwin_values['-pat_id_num-']
                custon_mr.addr=mr_editwin_values['-addr-']
                custon_mr.in_date=mr_editwin_values['-in_date-']
                custon_mr.dis_date=mr_editwin_values['-dis_date-']
                custon_mr.dis_group=mr_editwin_values['-dis_group-']
                custon_mr.dis_way=mr_editwin_values['-dis_way-']
                custon_mr.pd=mr_editwin_values['-pd-']
                custon_mr.doctor=mr_editwin_values['-doctor-']
                custon_mr.filing_time=mr_editwin_values['-filing_time-']
                custon_mr.id=mr_editwin['-id-'].Get()
            except ValueError as e:
                sg.PopupError(str(e),keep_on_top=True)
                continue
            
            esqlstr="update mrinfo set mr_num=?,hospital_num=?,pat_name=?,id_num=?,addr=?,in_date=?,dis_date=?,dis_group=?,dis_way=?,pd=?,doctor=?,filing_time=? where id=?"

            eparams=(custon_mr.mr_num,custon_mr.hospital_num,custon_mr.pat_name,custon_mr.id_num,custon_mr.addr,custon_mr.in_date,custon_mr.dis_date,custon_mr.dis_group,custon_mr.dis_way,custon_mr.pd,custon_mr.doctor,custon_mr.filing_time,custon_mr.id)

            try:
                rs=SQLHLPER.execute(esqlstr,*eparams)
            except Exception as ex:
                sg.PopupError(str(ex))

            if rs==1:
                mr_editwin_active=False
                mr_editwin.close()
                update_table()




    #--------------导出归档病案 ex_port------------------

    if event=='导出::-export-':

        exporting_filing=mainwin['-table-'].Get()
        wb=Workbook()
        ws=wb.active
        ws.append(headings)
        for row in exporting_filing:
            ws.append(row)
        file_path=os.path.dirname(__file__)+'/'+datetime.now().strftime('%y%m%d%H%M%S')
        file_path=sg.PopupGetFile('保存为',save_as=True,file_types=(('EXCEL','*.xlsx'),),default_path=file_path)
        if file_path!='' and not file_path is None:
            wb.save(file_path+'.xlsx')
            sg.Popup('ok!',auto_close=True,auto_close_duration=1)




    # -------------病案归档 mr_filing ---------

    if event=='-mr_filing-' and not filingwin_active:
        
        filingwin_active=True
        mr_filing_win=otherwin.MRFilingWindow()
    
    if filingwin_active:

        filwin_event,filwin_values=mr_filing_win.Read(timeout=100)

        if filwin_event is None or filwin_event=='-cancel-':
            filingwin_active=False
            mr_filing_win.close()

        if filwin_event=='-in_date_calendar-':
            choosen_time=otherwin.PopupCalendar(format='%Y-%m-%d')
            mr_filing_win['-in_date-'].Update(choosen_time)

        if filwin_event=='-dis_date_calendar-':
            choosen_time=otherwin.PopupCalendar(format='%Y-%m-%d')
            mr_filing_win['-dis_date-'].Update(choosen_time)

        if filwin_event=='-filing_time_calendar-':
            choosen_time=otherwin.PopupCalendar()
            mr_filing_win['-filing_time_date-'].Update(choosen_time)

        if filwin_event=='-save-' or filwin_event=='-savenew-':

            mr=MR()    #创建一个MR对象
            try:
                mr.mr_num=filwin_values['-mr_num-']
                mr.hospital_num=filwin_values['-hospital_num-']
                mr.pat_name=filwin_values['-pat_name-']
                mr.id_num=filwin_values['-pat_id_num-']
                mr.addr=filwin_values['-addr-']
                mr.in_date=filwin_values['-in_date-']
                mr.dis_date=filwin_values['-dis_date-']
                mr.dis_group=filwin_values['-dis_group-']
                mr.dis_way=filwin_values['-dis_way-']
                mr.pd=filwin_values['-pd-']
                mr.doctor=filwin_values['-doctor-']
                mr.filing_time=filwin_values['-filing_time-']
            except ValueError as e:
                sg.PopupError(str(e),keep_on_top=True)
                continue
                                
            fsqlstr="insert into mrinfo(mr_num,hospital_num,pat_name,id_num,addr,in_date,dis_date,dis_group,dis_way,pd,doctor,filing_time,is_on) values(?,?,?,?,?,?,?,?,?,?,?,?,?)"

            fparams=(mr.mr_num,mr.hospital_num,mr.pat_name,mr.id_num,mr.addr,mr.in_date,mr.dis_date,mr.dis_group,mr.dis_way,mr.pd,mr.doctor,mr.filing_time,1)

            try:
                rs=SQLHLPER.execute(fsqlstr,*fparams)
            except Exception as ex:
                sg.PopupError(str(ex))

            if rs==1:
                if filwin_event=='-save-':
                    filingwin_active=False
                    mr_filing_win.close()
                elif filwin_event=='-savenew-':
                    mr_filing_win['-mr_num-'].Update('')
                    mr_filing_win['-hospital_num-'].Update('')
                    mr_filing_win['-pat_name-'].Update('')
                    mr_filing_win['-pat_id_num-'].Update('')
                    mr_filing_win['-addr-'].Update('')
                    mr_filing_win['-in_date-'].Update('')
                    mr_filing_win['-dis_date-'].Update('')
                    mr_filing_win['-dis_group-'].Update('')
                    mr_filing_win['-dis_way-'].Update('')
                    mr_filing_win['-pd-'].Update('')
                    mr_filing_win['-doctor-'].Update('')
                    mr_filing_win['-mr_num-'].set_focus(True)
                    continue

                
    
    # ------------病案借阅历史记录 mr_borrowed_all--------

    if event=='-mr_borrowed_log-' and not mr_bor_logwin_active:
        
        mr_bor_logwin_active=True
        mr_bor_logwin=otherwin.MRBorrowLogWindow()

    if mr_bor_logwin_active:
        
        mr_bor_logwin_event,mr_bor_logwin_values=mr_bor_logwin.Read(timeout=100)

        if mr_bor_logwin_event==sg.WIN_CLOSED:
            mr_bor_logwin_active=False
            mr_bor_logwin.close()
        
        if mr_bor_logwin_event=='-search-':
            search_vars=mr_bor_logwin_values['-in-']

            bsqlstr="SELECT mrinfo.MR_NUM,mrinfo.HOSPITAL_NUM,mrinfo.PAT_NAME,mrborrow.BORROWER,mrinfo.DIS_DATE,mrborrow.BORROW_TIME,ifnull(mrborrow.BACK_TIME,'') from mrborrow left outer join mrinfo ON mrborrow.MRINFO_ID=mrinfo.ID where  HOSPITAL_NUM=:var1 or MR_NUM=:var1 or PAT_NAME like :var2 or borrower like :var2 order by back_time,borrow_time desc"

            rs=SQLHLPER.selectall(bsqlstr,**{'var1':search_vars,'var2':'%'+search_vars+'%'})

            if rs:
                mr_bor_logwin['-emp-'].set_size(size=(1,1))

                tmp_t_data=[list(r) for r in rs]
                mr_bor_logwin['-table-'].Update(num_rows=min(len(tmp_t_data),20))
                mr_bor_logwin['-table-'].Update(tmp_t_data)
                mr_bor_logwin['-table_col-'].Update(visible=True)
                mr_bor_logwin['-display_table_info-'].Update('共 {} 行记录'.format(len(rs)))



    # -------------查阅病案归档率 filingratewin-------------------

    if event=='-mr_filingrate-' and not filingratewin_active:

        filingratewin_active=True
        filingratewin=otherwin.FilingRateWindow()

    if filingratewin_active:

        filingratewin_event,filingratewin_values=filingratewin.Read(timeout=100)

        if filingratewin_event==sg.WIN_CLOSED:
            filingratewin_active=False
            filingratewin.close()

        if filingratewin_event=='-firstdate_calendar-':
            choosen_time=otherwin.PopupCalendar(format='%Y-%m-%d')
            filingratewin['-firstdate-'].Update(choosen_time)

        if filingratewin_event=='-lastdate_calendar-':
            choosen_time=otherwin.PopupCalendar(format='%Y-%m-%d')
            filingratewin['-lastdate-'].Update(choosen_time)

        if filingratewin_event=='-search-':
            
            tmp_firstdate=datetime.strptime(filingratewin_values['-firstdate-'],'%Y-%m-%d').date()
            tmp_lastdate=datetime.strptime(filingratewin_values['-lastdate-'],'%Y-%m-%d').date()
           
            if tmp_firstdate>tmp_lastdate:
                sg.PopupError('截止日期应大于等于起始日期')
                continue

            filingrate_list=otherwin.FilingCalculator(tmp_firstdate,tmp_lastdate,filingratewin_values['-disgroup-'])

            # 计算归档病案数量,即第2列之和
            filing_counts=0
            for f in filingrate_list:
                filing_counts+=f[1]

            filingratewin['-table-'].Update(filingrate_list)
            filingratewin['-displaynums-'].Update('期间归档病案共计 {} 份'.format(filing_counts))

        if filingratewin_event=='导出::-report-':
            filing_rate_data=filingratewin['-table-'].Get()
            # df=pds.DataFrame(filing_rate_data,columns=['出院科室/医生','归档病案数','2日归档率%','3日归档率%','7日归档率%'])
            wb=Workbook()
            ws=wb.active
            ws.append(['出院科室/医生','归档病案数','2日归档率%','3日归档率%','7日归档率%'])
            for row in filing_rate_data:
                ws.append(row)
            file_path=os.path.dirname(__file__)+'/'+datetime.now().strftime('%y%m%d%H%M%S')
            file_path=sg.PopupGetFile('保存为',save_as=True,file_types=(('EXCEL','*.xlsx'),),default_path=file_path)
            if file_path!='' and not file_path is None:
                wb.save(file_path+'.xlsx')
                sg.Popup('ok!',auto_close=True,auto_close_duration=1)
            # df.to_excel(file_path,'Sheet1',index=False,engine='openpyxl')




    # -------------选项设置 optionwinwin--------------------------

    if event=='-option-' and not optionwin_active:

        optionwin_active=True
        optionwin=otherwin.OptionWindow()

    if optionwin_active:

        optionwin_event,optionwin_values=optionwin.Read(timeout=100)

        if optionwin_event==sg.WIN_CLOSED:
            optionwin_active=False
            optionwin.close()

        if optionwin_event=='-save_dayoff-' and len(optionwin_values['-in_dayoff-'])>=8:

            in_dayoff_list=optionwin_values['-in_dayoff-'].split()

            errmsg='无效的日期,被忽略：'
            valid_date_mr=MR()
            rexp='^20[123][0-9][01][0-9][0-3][0-9]$'
            for item in in_dayoff_list:

                if re.match(rexp,item) is None:
                    errmsg+=item+'\n'
                    continue

                errmsg2=valid_date_mr.validdate(item[:4],item[4:6],item[6:])
                if not errmsg2 is None:
                    errmsg+=errmsg2+'\n'
                    continue

                sqlstr="select offday from dayoff where offday=:day"
                rs=SQLHLPER.selectall(sqlstr,**{'day':str(datetime.strptime(item,'%Y%m%d').date())})
                if len(rs)>0:
                    errmsg+=item+" 已存在\n"
                    continue

                sqlstr="insert into dayoff(offday) values(?)"
                print(str(datetime.strptime(item,'%Y%m%d').date()))
                SQLHLPER.execute(sqlstr,*(str(datetime.strptime(item,'%Y%m%d').date()),))
                dayoff_list=otherwin.GetDayOff()
                optionwin['-dayoff_listbox-'].Update(dayoff_list)
                optionwin['-in_dayoff-'].Update('')

            if errmsg!='无效的日期,被忽略：':
                sg.PopupError(errmsg)
                continue


        if optionwin_event=='删除::-del_dayoff-':
            
            listbox_values=optionwin_values['-dayoff_listbox-']
            for day in listbox_values:
                sqlstr="delete from dayoff where offday=?"
                SQLHLPER.execute(sqlstr,*(day,))
            dayoff_list=otherwin.GetDayOff()
            optionwin['-dayoff_listbox-'].Update(dayoff_list)


        if optionwin_event=='-save_groupname-' and len((optionwin_values['-in_groupname-']).strip())>0:

            sqlstr="insert into groupname(GROUP_NAME) values(?)"
            SQLHLPER.execute(sqlstr,*(optionwin_values['-in_groupname-'],))
            group_names=otherwin.GetGroupNames()
            optionwin['-groupnames_listbox-'].Update(group_names)
            optionwin['-in_groupname-'].Update('')

        if optionwin_event=='删除::-del_groupname-':

            sqlstr="delete from groupname where GROUP_NAME=?"
            for gn in optionwin_values['-groupnames_listbox-']:
                SQLHLPER.execute(sqlstr,*(gn,))
                group_names=otherwin.GetGroupNames()
                optionwin['-groupnames_listbox-'].Update(group_names)

        if optionwin_event=='修改::-edit-' and len(optionwin_values['-groupnames_listbox-'])>0:

            old_groupname=optionwin_values['-groupnames_listbox-'][0]
            new_groupname=sg.PopupGetText('原科室名称：'+old_groupname)
            if new_groupname=='' or new_groupname is None:
                continue
            sqlstr="update groupname set GROUP_NAME=? where GROUP_NAME=?"
            SQLHLPER.execute(sqlstr,*(new_groupname,old_groupname))
            group_names=otherwin.GetGroupNames()
            optionwin['-groupnames_listbox-'].Update(group_names)




    # -------------查阅病历复印历史记录 mr_cop_logwin-----------

    if event=='-mr_copyed_log-' and not mr_cop_logwin_active:

        mr_cop_logwin_active=True
        mr_cop_logwin=otherwin.MRCopyedLogWindow()

    if mr_cop_logwin_active:

        mr_cop_logwin_event,mr_cop_logwin_values=mr_cop_logwin.Read(timeout=100)

        if mr_cop_logwin_event==sg.WIN_CLOSED:
            mr_cop_logwin_active=False

        if mr_cop_logwin_event=='-search-':

            def tmp_search():
                sqlstr="select mr_num,hospital_num,pat_name,copyer_name,copyer_id_num,relation,purpose,copy_time,mrcopyrecord.id from mrcopyrecord left outer join mrinfo on mrinfo_id=mrinfo.id where mr_num=:vas1 or hospital_num=:vas1 or pat_name like :vas2 or id_num like :vas2 order by copy_time desc"
                rs=SQLHLPER.selectall(sqlstr,**{'vas1':mr_cop_logwin_values['-in-'],'vas2':'%{}%'.format(mr_cop_logwin_values['-in-'])})
                copyed_list=[list(item) for item in rs]
                mr_cop_logwin['-table-'].Update(copyed_list)
                mr_cop_logwin['-table-'].Update(num_rows=min(20,len(copyed_list)))
                mr_cop_logwin['-disp_table_info-'].Update('共{}行记录'.format(len(copyed_list)))

            tmp_search()

        if mr_cop_logwin_event=='删除::-del-':

            table_data=mr_cop_logwin['-table-'].Get()
            current_r=mr_cop_logwin_values['-table-']
            sqlstr="delete from mrcopyrecord where id=?"
            for row in current_r:
                rs=SQLHLPER.execute(sqlstr,*(table_data[row][8],))
            if rs>0:
                tmp_search()





    # -------------其它档案借阅历史查阅窗口 arc_bor_logwin----------------

    if event=='-arc_bor_log-' and not arc_bor_logwin_active:

        arc_bor_logwin_active=True
        arc_bor_logwin=otherwin.ArcBorrowLogWinow()
        
    if arc_bor_logwin_active:

        arc_bor_logwin_event,arc_bor_logwin_values=arc_bor_logwin.Read()

        if arc_bor_logwin_event==sg.WIN_CLOSED:

            arc_bor_logwin_active=False
            arc_bor_logwin.close()

        if arc_bor_logwin_event=='-search-':

            sqlstr="select arc_id,arc_content,borrower,borrow_time,ifnull(back_time,''),id from archivesborrow where arc_id like :vas or arc_content like :vas or borrower like :vas order by back_time,borrow_time desc"
            rs=SQLHLPER.selectall(sqlstr,**{'vas':'%{}%'.format(arc_bor_logwin_values['-in-'])})
            arc_borrow_list=[list(item) for item in rs]

            arc_bor_logwin['-table-'].Update(arc_borrow_list)
            arc_bor_logwin['-disp_table_info-'].Update('共 {} 条记录'.format(len(arc_borrow_list)))

        if arc_bor_logwin_event=='归还::-back-' and not arc_backwin_active and len(arc_bor_logwin_values['-table-'])>0:

            arc_backwin_active=True
            tmp_table_data=arc_bor_logwin['-table-'].Get()
            current_row=tmp_table_data[arc_bor_logwin_values['-table-'][0]]
            arc_backwin=otherwin.ArcBackWindow(current_row[5],current_row[0],current_row[1])

        if arc_backwin_active:

            rexp=r'^[12][09][0-9]{2}-[01][0-9]-[0-3][0-9](\s{1,4}[0-2][0-9]:[0-5][0-9]:[0-5][0-9])?$'
            arc_backwin_event,arc_backwin_values=arc_backwin.Read()

            if arc_backwin_event==sg.WIN_CLOSED or arc_backwin_event=='-cancel-':
                arc_backwin_active=False
                arc_backwin.close()

            if arc_backwin_event=='-save-':

                backtime=arc_backwin_values['-back_time-']
                if re.match(rexp,backtime) is None:
                    sg.PopupError('无效日期！')
                    continue

                err=MR().validdate(backtime[:4],backtime[5:7],backtime[8:10])
                if not err is None:
                    sg.PopupError(err)
                    continue

                sqlstr="update archivesborrow set back_time=? where id=?"
                SQLHLPER.execute(sqlstr,*(backtime,arc_backwin['-id-'].Get()))
                arc_backwin.close()

                sqlstr="select arc_id,arc_content,borrower,borrow_time,ifnull(back_time,''),id from archivesborrow where arc_id like :vas or arc_content like :vas or borrower like :vas order by back_time,borrow_time desc"
                rs=SQLHLPER.selectall(sqlstr,**{'vas':'%{}%'.format(arc_bor_logwin_values['-in-'])})
                new_t_data=[list(item) for item in rs]
                arc_bor_logwin['-table-'].Update(new_t_data)                




    # -------------其它档案借阅登记窗口 arc_borrowwin-----------------

    if event=='-arc_borrow-' and not arc_borrowwin_active:

        arc_borrowwin_active=True
        arc_borrowwin=otherwin.ArcBorrowReginWindow()

    if arc_borrowwin_active:

        regx=r'^[12][09][0-9]{2}-[01][0-9]-[0-3][0-9](\s{1,4}[0-2][0-9]:[0-5][0-9]:[0-5][0-9])?$'

        arc_borrowwin_event,arc_borrowwin_values=arc_borrowwin.Read(timeout=100)

        if arc_borrowwin_event in (sg.WIN_CLOSED,'-cancel-'):
            arc_borrowwin_active=False
            arc_borrowwin.close()

        if arc_borrowwin_event=='-borrow_time_calendar-':
            choosen_time=otherwin.PopupCalendar()
            arc_borrowwin['-borrow_time-'].Update(choosen_time)

        if arc_borrowwin_event=='-save-' or arc_borrowwin_event=='-savenew-':

            borrowtime=arc_borrowwin_values['-borrow_time-']
            arc_num=arc_borrowwin_values['-archives_num-']
            arc_contents=arc_borrowwin_values['-archives_contents-']
            arc_borrower=arc_borrowwin_values['-borrower-']
            
            if arc_num=='' and arc_contents=='':
                sg.PopupError('档案号、档案描述 至少填一项！')
                continue

            if arc_borrower=='':
                sg.PopupError('借阅人必填！')
                continue

            if re.match(regx,borrowtime) is None:
                sg.PopupError('无效日期:'+borrowtime)
                continue

            # 继续验证日期有效性
            err=MR().validdate(borrowtime[:4],borrowtime[5:7],borrowtime[8:10])
            if not err is None:
                sg.PopupError(err)
                continue

            strsql="insert into archivesborrow(arc_id,arc_content,borrower,borrow_time) values(?,?,?,?)"
            rs=SQLHLPER.execute(strsql,*(arc_num,arc_contents,arc_borrower,borrowtime))
            if rs<1:
                sg.PopupError('发生未知错误，保存失败！')

            if arc_borrowwin_event =='-savenew-':
                arc_borrowwin['-archives_num-'].Update('')
                arc_borrowwin['-archives_contents-'].Update('')
                arc_borrowwin['-borrower-'].Update('')
                arc_borrowwin['-archives_num-'].set_focus(True)

            elif arc_borrowwin_event=='-save-':
                arc_borrowwin_active=False
                arc_borrowwin.close()



    # --------------帮助信息 helpwin-----------------------------------

    if event=='-help-' and not helpwin_active:
        helpwin_active=False
        sg.PopupOK('帮助','MRMS:简洁且功能完整的档案示踪系统\n\n包括病案归档、病案借阅、病案归还、病案复印，以及其它档案的借阅登记与归还。\n\n较多常用功能于右键快捷菜单中。\n\n版权所有人：张海洲')



mainwin.close()



